﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using EntityLayer;

namespace DynamicObject_t
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        List<IClassEntity> _entities;

        private void Form1_Load(object sender, EventArgs e)
        {
            bool Error;
            _entities = Options.Helper.GetEntities(out Error);
            if (Error) { MessageBox.Show("Error while loading assemblies, look at log file for details."); this.Close(); return; }
            dataGridView1.DataSource = GetObjects(_entities);          
            
        }


        List<IObject> GetObjects(List<IClassEntity> asseblies)
        {
            List<IObject> result = new List<IObject>();
            foreach (var g in asseblies)
                result.AddRange(g.Objects);
            return result;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                var obj = (from i in _entities where i.Name == dataGridView1.SelectedRows[0].Cells[1].Value.ToString() select i).FirstOrDefault();
                obj.Edit((int)dataGridView1.SelectedRows[0].Cells[0].Value).ShowDialog();
                dataGridView1.DataSource = GetObjects(_entities);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            ClassSelect frm = new ClassSelect(_entities);
            frm.ShowDialog();
            dataGridView1.DataSource = GetObjects(_entities);
        }

        private void button3_Click(object sender, EventArgs e)
        {

            if (dataGridView1.SelectedRows.Count>0&&MessageBox.Show("Are you sure?", "Removing", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var obj = (from i in _entities where i.Name == dataGridView1.SelectedRows[0].Cells[1].Value.ToString() select i).FirstOrDefault();
                obj.Delete((int)dataGridView1.SelectedRows[0].Cells[0].Value);
                dataGridView1.DataSource = GetObjects(_entities);
            }
        }
    }
}
